package com.bestom.videoplay.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.bestom.videoplay.MediaApplication;
import com.bestom.videoplay.R;
import com.bestom.videoplay.adapter.BleAdapter;
import com.bestom.videoplay.callback.BTGattCallback;

import java.util.ArrayList;
import java.util.List;

import static android.bluetooth.BluetoothDevice.TRANSPORT_LE;

public class BlueToothActivity extends AppCompatActivity {

    private static final String TAG = "BlueToothActivity";

    private static final long SCAN_TIME = 10000;
    private static BlueToothActivity self;
    private Context mContext;
    private boolean isScaning = false;
    private BluetoothAdapter mBluetoothAdapter;

    public static BlueToothActivity getInstance(){
        return self;
    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth);
        mContext = this;
        self = this;
        initView();
        initData();
        mBluetoothAdapter = initBluetoothAdapter();

        if (!isAdapterEnabled()){
            Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent,0);
        }
        scanDevice();
    }

    private BluetoothAdapter initBluetoothAdapter(){
        BluetoothManager mBluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        return mBluetoothManager.getAdapter();
    }

    /**
     * 检查权限
     */
    private boolean isAdapterEnabled() {
        return BluetoothAdapter.getDefaultAdapter().isEnabled();
    }


    private List<BluetoothDevice> deviceList;
    private List<Integer> mRssis;
    private BleAdapter mAdapter;
    private ListView bleListView;
    private Toolbar toolbar;

    private void initData() {
        deviceList = new ArrayList<>();
        mRssis = new ArrayList<>();
        mAdapter = new BleAdapter(BlueToothActivity.this, deviceList, mRssis);
        bleListView.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();

        toolbar.setTitle(getString(R.string.ble_toolbar_title));

        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    private BluetoothGatt mBluetoothGatt;
    private void initView() {
        toolbar = findViewById(R.id.toolbar);
        bleListView = findViewById(R.id.device_list);
        bleListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (!isScaning) stopScanDevice();

                if (mBluetoothGatt != null) disconnect();

                BluetoothDevice bluetoothDevice = deviceList.get(position);

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                    mBluetoothGatt = bluetoothDevice.connectGatt(mContext,true, new BTGattCallback(), TRANSPORT_LE);
                }else {
                    mBluetoothGatt = bluetoothDevice.connectGatt(mContext,true,new BTGattCallback());
                }
                MediaApplication.getApplication().setmBluetoothGatt(mBluetoothGatt);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.bluetooth,menu);
        menu.findItem(R.id.search).setVisible(isScaning );
        menu.findItem(R.id.dis_search).setVisible(!isScaning);
        menu.findItem(R.id.setMtu).setVisible(isScaning);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        switch (item.getItemId()){
            case android.R.id.home:
                onBackPressed();
                break;
            case R.id.search:
                scanDevice();
                break;
            case R.id.dis_search:
                stopScanDevice();
                break;
            default:
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    /**
     * 开始扫描 10秒后自动停止
     * */
    private Runnable scannable;
    private Handler handler = new Handler();

    private void scanDevice(){

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                clear();
            }
        });

        if (isAdapterEnabled()) {
            isScaning=false;
            mBluetoothAdapter.startLeScan(scanCallback);
            self.invalidateOptionsMenu();
        } else {
            Toast.makeText(getApplicationContext(),"请打开蓝牙",Toast.LENGTH_SHORT).show();
            return;
        }
        scannable = new Runnable() {
            @Override
            public void run() {
                stopScanDevice();
            }
        };
        handler.postDelayed(scannable, SCAN_TIME);

    }

    /**
     * 停止扫描
     * */
    private void stopScanDevice(){
        if (scannable != null)
            handler.removeCallbacks(scannable);

        isScaning=true;
        mBluetoothAdapter.stopLeScan(scanCallback);
        self.invalidateOptionsMenu();
    }

    BluetoothAdapter.LeScanCallback scanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {

            if (!deviceList.contains(device)){
                deviceList.add(device);
                mRssis.add(rssi);
                mAdapter.notifyDataSetChanged();
            }

        }
    };

    public void disconnect(){
        mBluetoothGatt.disconnect();
    }

    public void clear(){
        deviceList.clear();
        mAdapter.notifyDataSetChanged();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();

        deviceList.clear();
        if (isScaning) {
            isScaning = false;
        }
        if (scannable != null) {
            handler.removeCallbacks(scannable);
        }

    }

}
